package com.techsoul.module.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.CategoryVo;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.goods.mapper.BasicSkuMapper;
import com.techsoul.module.goods.mapper.BasicSpuMapper;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.goods.mapper.SpuMapper;

import com.techsoul.module.goods.pojo.entity.*;
import com.techsoul.module.goods.pojo.vo.SkuVo;
import com.techsoul.module.pms.mapper.GoodsSupplierMapper;
import com.techsoul.module.pms.pojo.entity.GoodsSupplier;
import com.techsoul.module.system.service.IGeneralSeqService;
import com.techsoul.module.goods.pojo.param.SpuSaveParam;
import com.techsoul.module.goods.pojo.param.SpuSearchParam;
import com.techsoul.module.goods.pojo.vo.SpuVo;
import com.techsoul.module.goods.service.ICategoryService;
import com.techsoul.module.goods.service.ISpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品 Service实现
 *
 * @author liuen
 * @date 2020-12-15
 */
@Service
@Transactional(readOnly = true)
public class SpuServiceImpl implements ISpuService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SpuMapper mapper;
    @Autowired
    private SkuMapper skumapper;
    @Autowired
    private BasicSkuMapper basicSkuMapper;
    @Autowired
    private BasicSpuMapper basicSpuMapper;
    @Autowired
    private GoodsSupplierMapper goodsSupplierMapper;


    @Autowired
    private TokenService tokenService;

    @Autowired
    private IGeneralSeqService generalSeqService;
    @Autowired
    private ICategoryService categoryService;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(SpuSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        Spu entity = new Spu();
        BeanUtils.copyProperties(params, entity);

        //  entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        String spuid =   this.generalSeqService.generateSeq("spu");
        String bspuid =   this.generalSeqService.generateSeq("basicSpu");
        entity.setId(spuid);
        entity.preInsert(user.getId());

        // 完善分类名称
        CategoryVo categoryVo = categoryService.findById(entity.getCategoryId());
        if (categoryVo != null) {
            entity.setCategoryName(categoryVo.getCategoryFullName());
        }
        // 完善货号
        if (StringUtils.isBlank(params.getSn())) {
            entity.setSn(idWorker.nextId() + "");
        }
        if(!StringUtils.isNull(user.getSite())){
            entity.setSite(user.getSite());
        }else{
            entity.setSite(user.getOrgId());
        }
        if(StringUtils.isNull(params.getSupplierNo()))
        {
            entity.setSupplierNo(user.getSupplierId());
            entity.setSupplierName(user.getCompanyName());
        }

       BasicSpu basicSpu = new BasicSpu();
       BeanUtils.copyProperties(entity, basicSpu);
        basicSpu.setId(bspuid);
        basicSpu.preInsert(user.getId());
        basicSpu.setOriginalSupplierNo(user.getSupplierId());
        basicSpu.setOriginalSupplierName(user.getCompanyName());
        entity.setBasicId(bspuid);
        this.basicSpuMapper.insert(basicSpu);
        this.mapper.insert(entity);
        if(!StringUtils.isNull(entity.getSupplierNo())){
            GoodsSupplier goodsSupplier = new GoodsSupplier();
            goodsSupplier.setSupplierId(entity.getSupplierNo());
            goodsSupplier.setSupplierName(entity.getSupplierName());
            goodsSupplier.setSpuId(entity.getId());
            goodsSupplier.setBrandId(entity.getBrandId());
            goodsSupplier.setSn(entity.getSn());
            goodsSupplier.setGoodsType(entity.getDeliveryType());
            goodsSupplier.setSpec(entity.getSpecs());
            goodsSupplier.setBrandName(entity.getBrandName());
            goodsSupplier.preInsert(user.getId());
            this.goodsSupplierMapper.insert(goodsSupplier);
        }



        return entity.getId();
    }

    @Transactional(readOnly = false)
    @Override
    public String insertSku(SpuSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        Spu entity = this.mapper.selectById(params.getId());

        if(params.getSkuList()!=null&&params.getSkuList().size()>0){
            for(int i=0;i<params.getSkuList().size();i++){
                SkuVo skuVo = params.getSkuList().get(i);

                // sku = this.skumapper.selectBySpuIdAndSpec(params.getId(),params.getSpecs());
                //  entity.setId(idWorker.nextId() + "").preInsert(user.getId());
                if(skuVo.getId() ==null||skuVo.getId()==""){
                    Sku sku = new Sku();
                    BasicSku basicSku = new BasicSku();
                    String skuid =   this.generalSeqService.generateSeq("sku");
                    String basicSkuId =   this.generalSeqService.generateSeq("basicSku");
                    sku.setId(skuid);
                    sku.setSpuId(entity.getId());
                    sku.preInsert(user.getId());
                    sku.setBrandId(params.getBrandId());
                    sku.setBrandName(params.getBrandName());
                    sku.setCategoryId(params.getCategoryId());
                    sku.setCategoryName(params.getCategoryName());
                    sku.setSite(user.getSite());
                    sku.setSkuName(skuVo.getSkuName());
                    sku.setSpec(skuVo.getSpec());
                    sku.setWeight(skuVo.getWeight());
                    // 完善分类名称
                    sku.preInsert(user.getId());
                    BeanUtils.copyProperties(sku, basicSku);
                    basicSku.setId(basicSkuId);
                    basicSku.setOriginalSupplierNo(user.getSupplierId());
                    basicSku.setOriginalSupplierName(user.getCompanyName());
                    sku.setBasicId(basicSkuId);
                    basicSku.setSpuId(entity.getBasicId());
                    basicSku.preInsert(user.getId());
                    this.basicSkuMapper.insert(basicSku);
                    this.skumapper.insert(sku);
                }

            }


        }

        return entity.getId();
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }
    /**
     * 批量作废
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer logicalDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            for(int i=0;i<idList.size();i++){
                String id = (String)idList.get(i);
                Spu entityFromDb = this.mapper.selectById(id);

                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

                entityFromDb.preUpdate(user.getId());
                entityFromDb.setIsValid("0");
                this.mapper.updateById(entityFromDb);
            }
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(SpuSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        Spu entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        // 完善分类名称
        CategoryVo categoryVo = categoryService.findById(entityFromDb.getCategoryId());
        if (categoryVo != null) {
            entityFromDb.setCategoryName(categoryVo.getCategoryFullName());
        }
        // 完善货号
        if (StringUtils.isBlank(params.getSn())) {
            entityFromDb.setSn(idWorker.nextId() + "");
        }
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public SpuVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<SpuVo> findAll(SpuSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SpuVo> findAll(SpuSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

}
